<template>
  <div>
    <span class="mr-ls">是否Ant预览：<a-switch v-model:checked="isAImage" /></span>
    <span>是否可选择多个图片：<a-switch v-model:checked="isMultiple" /></span>
  </div>
  <a-divider />
  <div class="img-container">
    <template v-if="isMultiple">
      <div v-for="(item, index) of avatarUrl" :key="index" class="mutiple-box">
        <a-image :src="item" class="multiple-img" v-if="isAImage" />
        <img :src="item" class="multiple-img" v-else />
        <close-outlined class="close" @click="deleteImg(index)" />
      </div>
    </template>
    <div class="avatar-uploader">
      <input type="file" class="upload-img" name="avatar" ref="avatarInput" :multiple="isMultiple" @change="changeImage($event)" accept="image/jpeg,image/jpg,image/png" />
      <img v-if="avatarUrl.length === 1 && !isMultiple" :src="avatarUrl[0]" class="avatar" />
      <plus-outlined v-else class="icon"></plus-outlined>
    </div>
  </div>
</template>
<script>
import { uploadImage } from '@/api/index.js';
import { defineComponent, ref } from 'vue';
import { PlusOutlined, CloseOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
export default defineComponent({
  components: {
    PlusOutlined,
    CloseOutlined,
  },
  props: {
    imgUrl: {
      type: Array,
      default: [],
    },
    isMultiple: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['change-image'],
  setup(props, ctx) {
    const avatarUrl = props.imgUrl;
    const isMultiple = ref(props.isMultiple);
    const isAImage = ref(false);
    const upload = (imageData, imageName) => {
      uploadImage({ imageData: imageData, imageName: imageName })
        .then((item) => {
          avatarUrl.push(item.data);
          if (isMultiple) {
            ctx.emit('change-image', avatarUrl);
          } else {
            ctx.emit('change-image', item.data);
          }
        })
        .catch((err) => {
          if (err) {
            message.error('上传失败！');
          }
        });
    };

    const deleteImg = (index) => {
      avatarUrl.splice(index, 1);
    };

    const changeImage = (event) => {
      const file = Array.prototype.slice.call(event.target.files);
      let isCanUpload = true;
      if (isMultiple) {
        file.forEach((item) => {
          if (!uploadLimit(item)) {
            isCanUpload = false;
          }
        });
      } else {
        isCanUpload = this.uploadLimit(file[0]);
      }

      if (file.length > 0 && isCanUpload) {
        if (isMultiple) {
          file.forEach((ele) => {
            setUpload(ele);
          });
        } else {
          setUpload(file[0]);
        }
      }
    };

    const setUpload = (file) => {
      const reader = new FileReader();
      const imgPath = file.name;
      reader.readAsDataURL(file);
      reader.onload = function (e) {
        // 这里的this 指向reader
        const imgBase64 = this.result;
        upload(imgBase64, imgPath);
      };
    };

    const uploadLimit = (file) => {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        message.error('上传头像图片只能是 JPG或PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        message.error('单张图片大小不能超过 2MB!');
        return false;
      }
      return (isPNG || isJPG) && isLt2M;
    };
    return {
      avatarUrl,
      isMultiple,
      isAImage,
      deleteImg,
      changeImage,
    };
  },
});
</script>
<style lang="less" scoped>
.img-container {
  //   @include flex-box(flex-start, center);
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.avatar-uploader {
  width: 80px;
  height: 80px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  //   @include flex-box(center, center);

  ::v-deep .upload-img {
    position: absolute;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
  }

  .avatar {
    width: 100%;
    height: 100%;
    margin: auto;
  }

  .icon {
    margin: 0 auto;
  }
}

.mutiple-box {
  position: relative;
  width: 80px;
  height: 80px;
  margin-right: 2px;

  .multiple-img {
    width: 100%;
    height: 100%;
    display: block;
  }

  .close {
    width: 15px;
    height: 15px;
    border-radius: 0 0 0 12px;
    position: absolute;
    text-align: center;
    top: 0;
    right: 0;
    color: #fff;
    background-color: gray;
    cursor: pointer;
  }
}
</style>
